<template>
  <div class="material-management">
    <div class="filter-container">
      <div class="status-filter">
        <button
          v-for="status in statusOptions"
          :key="status.value"
          @click="changeStatus(status.value)"
          :class="{ active: currentStatus === status.value }"
        >
          {{ status.label }}
        </button>
      </div>

      <div class="pagination">
        <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
        <span class="page-info"
          >第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span
        >
        <button @click="nextPage" :disabled="currentPage === totalPages">
          下一页
        </button>
      </div>
    </div>

    <div class="material-list">
      <div
        class="material-card"
        v-for="item in orderList"
        :key="item.id"
        :class="(item.has_material == '2' || item.has_material == '1') ? 'finished' : ''"
      >
        <div class="card-header">
          <h3 class="card-title">{{ item.customer_name }} - {{ item.type }}</h3>
          <span class="status-badge" :class="getStatusClass(item)">{{
            getStatusText(item)
          }}</span>
        </div>

        <div class="card-content">
          <div class="info-row">
            <span class="label">订单号:</span>
            <span class="value">{{ item.order_number }}</span>
          </div>
          <div class="info-row">
            <span class="label">日期:</span>
            <span class="value">{{
              formatDateRange(item.start_date, item.end_date)
            }}</span>
          </div>
          <div class="info-row">
            <span class="label">渠道:</span>
            <span class="value">{{ item.channel || "未分配" }}</span>
          </div>
        </div>

        <div class="action-row">
          <div class="action-buttons">
            <button
              class="secondary-btn"
              v-if="item.has_material === '0'"
              :class="{ disabled: item.has_material != '0' }"
              @click="showDialog('upload', item)"
            >
              上传素材
            </button>
            <button
              v-if="item.has_material != '0'"
              class="secondary-btn"
              @click="showDialog('material', item)"
            >
              查看素材
            </button>
            <button
              :class="{ disabled: item.has_material == '2' }"
              class="secondary-btn"
              @click="setNoBackup(item)"
            >
              无需备份
            </button>
          </div>

          <router-link
            class="detail-btn"
            :to="`/material/detail/?id=${item.id}`"
          >
            查看详情
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <path d="M5 12h14M12 5l7 7-7 7" />
            </svg>
          </router-link>
        </div>
        <div
          class="finishedText"
          v-if="item.has_material == '2' || item.has_material == '1'"
        >
          已完成
        </div>
      </div>
    </div>

    <MaterialsDialog
      v-if="showDialogFlag && dialogType !== 'detail'"
      :type="dialogType"
      :item="currentItem"
      @close="closeDialog"
      @submit="handleDialogSubmit"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { get } from "@/request";
import MaterialsDialog from "./MaterialsDialog.vue";
import { vConfirm } from "@/plugins/vConfirm";

// 状态选项
const statusOptions = [
  { value: "all", label: "全部" },
  { value: "0", label: "待提交" },
  { value: "1", label: "已提交" },
  { value: "2", label: "无需备份" },
];

// 当前选中的状态
const currentStatus = ref("all");

// 当前页码
const currentPage = ref(1);
// 每页显示数量
const pageSize = ref(12);

// 弹窗控制
const showDialogFlag = ref(false);
const dialogType = ref(""); // 'upload' | 'material' | 'detail'
const currentItem = ref({});

// 订单数据
const orderList = ref([]);
// 分页信息
const paginationInfo = ref({
  total: 0,
  page: 1,
  pageSize: 10,
  totalPages: 1,
});

// 获取订单数据
const fetchOrders = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      has_material: currentStatus.value === "all" ? "" : currentStatus.value,
    };

    const res = await get("/order/list", params);
    if (res && res.code === 200) {
      orderList.value = res.data?.list || [];
      paginationInfo.value = res.data?.pagination || {
        total: 0,
        page: 1,
        pageSize: pageSize.value,
        totalPages: 1,
      };
    }
  } catch (error) {
    console.error("获取订单列表失败:", error);
  }
};

// 格式化日期范围
const formatDateRange = (startDate, endDate) => {
  if (startDate === endDate) return startDate;
  return `${startDate} 至 ${endDate}`;
};

// 获取状态文本
const getStatusText = (item) => {
  return item.has_material === "1"
    ? "已提交"
    : item.has_material === "2"
    ? "无需备份"
    : "待提交";
};

// 获取状态类名
const getStatusClass = (item) => {
  return item.has_material === "1"
    ? "submitted"
    : item.has_material === "2"
    ? "noback"
    : "pending";
};

// 改变状态筛选
const changeStatus = (status) => {
  currentStatus.value = status;
  currentPage.value = 1; // 切换状态时重置页码
  fetchOrders();
};

// 总页数
const totalPages = computed(() => {
  return paginationInfo.value.totalPages || 1;
});

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchOrders();
  }
};

// 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    fetchOrders();
  }
};

// 显示弹窗
const showDialog = (type, item) => {
  dialogType.value = type;
  currentItem.value = item;
  showDialogFlag.value = true;
};

// 关闭弹窗
const closeDialog = () => {
  showDialogFlag.value = false;
};

// 设为无需备份
const setNoBackup = (item) => {
  vConfirm({
    message: `确定要将订单 ${item.order_number} 设为无需备份吗？`,
  })
    .then((confirm) => {
      if (!confirm) return;

      request
        .post("/material/noback", { id: item.id })
        .then((res) => {
          if (res && res.code === 200) {
            // 重新获取当前页数据
            fetchOrders();
          }
        })
        .catch((error) => {
          console.error("设为无需备份失败:", error);
        });
    })
    .catch((e) => {});
};

// 处理弹窗提交
const handleDialogSubmit = (updatedItem) => {
  // 重新获取当前页数据
  fetchOrders();
  closeDialog();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchOrders();
});
</script>

<style lang="less" scoped>
.material-management {
  padding: 20px;
  background-color: var(--bs-bg-color);
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-filter {
  display: flex;
  gap: 10px;

  button {
    padding: 6px 14px;
    border: 1px solid var(--bs-border-color);
    background-color: white;
    color: var(--bs-nav-link-color);
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;

    &.active {
      background-color: var(--bs-theme-color);
      color: white;
      border-color: var(--bs-theme-color);
    }
  }
}

.material-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.material-card {
  background-color: white;
  border: 1px solid var(--bs-border-color);
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  position: relative;
  &.finished {
    background: #f0f0f0;
    box-shadow: none;
    border: 1px solid #ddd;
  }
  .finishedText {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 44px;
    transform: rotate(30deg);
    opacity: 0.6;
    pointer-events: none;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.card-title {
  font-size: 16px;
  color: var(--bs-dark-color);
  margin: 0;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.status-badge {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 12px;
  margin-left: 10px;
  white-space: nowrap;

  &.pending {
    background-color: #fff3e0;
    color: #ff9800;
  }

  &.submitted {
    background-color: #e8f5e9;
    color: #4caf50;
  }

  &.noback {
    background-color: #e3f2fd;
    color: #2196f3;
  }
}

.card-content {
  flex: 1;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
  font-size: 14px;

  .label {
    color: var(--bs-gray-color);
    margin-right: 8px;
    width: 60px;
  }

  .value {
    color: var(--bs-text-color);
  }
}

.action-row {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 15px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.secondary-btn {
  padding: 6px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  font-size: 12px;
  background-color: white;
  border: 1px solid var(--bs-border-color);
  color: var(--bs-text-color);

  &:hover {
    border-color: var(--bs-gray-color);
  }
  &.disabled {
    background: var(--bs-border-color);
    color: var(--bs-gray-color);
  }
}

.detail-btn {
  padding: 6px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  font-size: 12px;
  background-color: white;
  border: 1px solid var(--bs-theme-color);
  color: var(--bs-theme-color);
  text-decoration: none;
  text-align: center;

  &:hover {
    background-color: var(--bs-light-color);
    color: var(--bs-bg-color);
  }
}

.pagination {
  display: flex;
  align-items: center;
  gap: 10px;

  button {
    padding: 8px 16px;
    background-color: white;
    border: 1px solid var(--bs-border-color);
    color: var(--bs-link-color);
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover:not(:disabled) {
      background-color: #fff;
      border-color: var(--bs-shadow-color);
    }

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }
}

.page-info {
  color: var(--bs-text-color);
  font-size: 14px;
}
</style>